package org.noahsark.core.annotation;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.noahsark.core.annotation.AnnotationField;
import org.noahsark.core.annotation.AnnotationMethod;
import org.noahsark.core.annotation.AnnotationType;


public class AnnotationTest {

	public static void main(String[] args) {
		AnnotationTest test = new AnnotationTest();
		test.resolve();
		test.testDoIt();
	}

	/**
	 * ������λ�ȡע���Ӧע���е�ֵ
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void resolve() {
		try {
			// ��ȥ��Ӧ���� www.2cto.com
			Class clazz = Class.forName("cn.edu.my.seurat.annotation.AnnotationUser");
			// �ж�clazz�Ƿ����FirstAnno.classע��
			if (clazz.isAnnotationPresent(AnnotationType.class)) {
				// ���ڣ����ȡ���ע��
				AnnotationType annoType = (AnnotationType) clazz.getAnnotation(AnnotationType.class);
				System.out.println("AnnotationType value�� "+ annoType.typeValue());
			}

			// ��ȡ��������з���
			Method[] methods = clazz.getDeclaredMethods();
			// ��������ע��
			for (Method method : methods) {
				if (method.isAnnotationPresent(AnnotationMethod.class)) {
					AnnotationMethod annoMethod = method.getAnnotation(AnnotationMethod.class);
					System.out.println("AnnotationMethod value�� "+ annoMethod.methodValue());
				}
			}

			// ��ȡ��������������ֶ�
			Field[] fields = clazz.getDeclaredFields();
			// �����ֶ�ע��
			for (Field field : fields) {
				if (field.isAnnotationPresent(AnnotationField.class)) {
					AnnotationField annoField = field.getAnnotation(AnnotationField.class);
					System.out.println("AnnotationField value�� "+ annoField.fieldValue());
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * ����ע���е�ֵ�����Ҹ�ֵ��������Ի��߷���
	 */
	public void testDoIt() {
		try {
			AnnotationUser user = new AnnotationUser();
			Field field = user.getClass().getDeclaredField("userField");
			if (field.isAnnotationPresent(AnnotationField.class)) {
				AnnotationField annoField = field.getAnnotation(AnnotationField.class);

				// getDeclaredMethod()����һ�� Method ���󣬸ö���ӳ�� Class
				// �������ʾ�����ӿڵ�ָ��������������name ������һ��
				// String����ָ�����跽���ļ�ƣ�parameterTypes ������ Class �����һ������
				// Method doIt = user.getClass().getDeclaredMethod("doIt");
				// ���Ա���Ҫ��set ����get ���������ܵ���invoke����
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(),AnnotationUser.class);
				Method doIt = pd.getWriteMethod();

				if (null != doIt) {
					String value = annoField.fieldValue();
					doIt.invoke(user, value);
				}
			}
			user.doIt();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
